package org.jmsmith.utilities.io;

import java.io.*;
import java.nio.file.Files;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class Extractor {

    public static void main(String[] args) {
        try {
            // Open the zip file for reading
            FileInputStream fis = new FileInputStream(args[1]);
            ZipInputStream zipIn = new ZipInputStream(fis);

            // Extract each file in the directory
            ZipEntry entry = zipIn.getNextEntry();

            var curDir = new File(args[2]);

            if (!curDir.exists()) {
                Files.createDirectory(curDir.toPath());
            } else if (curDir.exists() && !curDir.isDirectory()) {
                throw new Exception("Extract to path is not a directory");
            }

            while (entry != null) {
                String filePath = args[2] + "/" + entry.getName();
                if (!entry.isDirectory()) {
                    extractFile(zipIn, filePath);
                } else {
                    File dir = new File(filePath);
                    dir.mkdir();
                }
                zipIn.closeEntry();
                entry = zipIn.getNextEntry();
            }

            // Close the ZipInputStream
            zipIn.close();
            fis.close();

            System.out.println("Directory decompressed successfully!");

        } catch (IOException e) {
            System.err.println("Failed to decompress directory: " + e.getMessage());
        } catch (Exception e) {
            System.err.println("Path to extract to is not a directory");
        }
    }

    static void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
        byte[] bytesIn = new byte[4096];
        int read;
        while ((read = zipIn.read(bytesIn)) != -1) {
            bos.write(bytesIn, 0, read);
        }
        bos.close();
    }
}